#!/usr/bin/env python3
import os
import shutil
import sys
import datetime
from pathlib import Path
import argparse


def count_files(directory: Path, extensions: list) -> dict:
    """统计目录中指定扩展名的文件数量
    
    Args:
        directory: 要扫描的目录路径
        extensions: 要统计的文件扩展名列表（不带点）
        
    Returns:
        包含各扩展名文件数量的字典
    """
    
    count = {ext: 0 for ext in extensions}
    for ext in extensions:
        count[ext] = len(list(directory.rglob(f"*{ext}")))
    return count


def main():

    parser = argparse.ArgumentParser()
    parser.add_argument('--source-dir', default=os.path.join(os.getcwd(), "downloads"), help='agiros下载目录路径 (默认: ./downloads)')
    parser.add_argument('--rpm-sources', default=os.path.join(os.getcwd(), "build/SOURCES"), help='编译sources目录 (默认: ./build/SOURCES)')
    parser.add_argument('--rpm-specs', default=os.path.join(os.getcwd(), "build/SPECS"), help='编译specs目录 (默认: ./build/SPECS)')

    args = parser.parse_args()

    source_dir = Path(args.source_dir).resolve()
    rpm_sources = Path(args.rpm_sources).resolve()
    rpm_specs = Path(args.rpm_specs).resolve()

    # 确保目录存在
    source_dir.mkdir(parents=True, exist_ok=True)
    rpm_sources.mkdir(parents=True, exist_ok=True)
    rpm_specs.mkdir(parents=True, exist_ok=True)

    # 查找所有.spec文件
    spec_files = list(source_dir.glob("*/*.spec"))
    spec_count = len(spec_files)

    # 查找同级.patch文件
    patch_files = set()
    for spec_file in spec_files:
        dir_path = spec_file.parent
        for patch in dir_path.glob("*.patch"):
            patch_files.add(patch)
    patch_files = sorted(patch_files)
    patch_count = len(patch_files)
    
    # 查找同级.tar.gz文件
    tar_files = set()
    for spec_file in spec_files:
        dir_path = spec_file.parent
        for tar in dir_path.glob("*.tar.gz"):
            tar_files.add(tar)
    tar_files = sorted(tar_files)
    tar_count = len(tar_files)

    # 查找同级.zip文件
    zip_files = set()
    for spec_file in spec_files:
        dir_path = spec_file.parent
        for zip in dir_path.glob("*.zip"):
            zip_files.add(zip)
    zip_files = sorted(zip_files)
    zip_count = len(zip_files)

    # 显示扫描结果
    print("\n扫描完成：")
    print(f"- 找到 {spec_count} 个.spec文件")
    print(f"- 找到 {tar_count} 个同级.tar.gz文件")
    print(f"- 找到 {zip_count} 个同级.zip文件")
    print(f"- 找到 {patch_count} 个同级.patch文件")     
    print()


    # 显示目标目录复制前的文件统计
    print("\n目标目录复制前的文件统计：")
    sources_before = count_files(rpm_sources, [".tar.gz", ".zip", ".patch"])
    specs_before = count_files(rpm_specs, [".spec"])
    print(f"- SOURCES 目录 ({rpm_sources}):")
    print(f"  .tar.gz: {sources_before['.tar.gz']}")
    print(f"  .zip:    {sources_before['.zip']}")   
    print(f"  .patch:  {sources_before['.patch']}")
    print(f"- SPECS 目录 ({rpm_specs}):")
    print(f"  .spec:   {specs_before['.spec']}")
    print()

    # 复制文件并计数
    copied_tar = 0
    copied_zip = 0
    copied_patch = 0
    copied_spec = 0

    # 复制.tar.gz文件
    print("开始复制.tar.gz文件...")
    for file in tar_files:
        try:
            shutil.copy2(file, rpm_sources)
            # print(f"已复制: {file}")
            copied_tar += 1
        except Exception as e:
            print(f"复制失败 {file}: {e}")

    # 复制.zip文件
    print("开始复制.zip文件...")
    for file in zip_files:
        try:
            shutil.copy2(file, rpm_sources)
            copied_zip += 1
        except Exception as e:
            print(f"复制失败 {file}: {e}")

    # 复制.patch文件
    print("开始复制同级.patch文件...")
    for file in patch_files:
        try:
            shutil.copy2(file, rpm_sources)
            # print(f"已复制 {copied_patch + 1}/{len(patch_files)}: {file}")
            copied_patch += 1
        except Exception as e:
            print(f"复制失败 {file}: {e}")

    # 复制.spec文件
    print("开始复制.spec文件...")
    for file in spec_files:
        try:
            shutil.copy2(file, rpm_specs)
            # print(f"已复制: {file}")
            copied_spec += 1
        except Exception as e:
            print(f"复制失败 {file}: {e}")

    # 显示复制后统计
    print("\n文件复制完成后的统计：")
    sources_after = count_files(rpm_sources, [".tar.gz", ".zip", ".patch"])
    specs_after = count_files(rpm_specs, [".spec"])
    print(f"- SOURCES 目录 ({rpm_sources}):")
    print(f"  .tar.gz: {sources_after['.tar.gz']}")
    print(f"  .zip:    {sources_after['.zip']}")   
    print(f"  .patch:  {sources_after['.patch']}")
    print(f"- SPECS 目录 ({rpm_specs}):")
    print(f"  .spec:   {specs_after['.spec']}")
    print()
    print("本次复制操作：")
    print(f"- 复制了 {copied_tar} 个.tar.gz文件")
    print(f"- 复制了 {copied_zip} 个.zip文件")
    print(f"- 复制了 {copied_patch} 个.patch文件")
    print(f"- 复制了 {copied_spec} 个.spec文件")  


if __name__ == "__main__":
    main()